package com.zsl.blog.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsl.blog.api.dao.mapper.SysUserMapper;
import com.zsl.blog.api.dao.pojo.SysUser;
import com.zsl.blog.api.service.LoginService;
import com.zsl.blog.api.service.SysUserService;
import com.zsl.blog.api.utils.ErrorCode;
import com.zsl.blog.api.vo.LoginUserVo;
import com.zsl.blog.api.vo.Result;
import com.zsl.blog.api.vo.params.LoginParam;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private LoginService loginService;

    @Override
    public SysUser findUser(String userName,String password) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getAccount,userName);
        wrapper.eq(SysUser::getPassword,password);
        wrapper.select(SysUser::getAccount,SysUser::getId,SysUser::getAvatar,SysUser::getNickname);
        wrapper.last("limit 1");
        return sysUserMapper.selectOne(wrapper);
    }

    @Override
    public SysUser findUserById(Long id) {
         SysUser sysUser = sysUserMapper.selectById(id);
         if(null==sysUser){
             sysUser = new SysUser();
             sysUser.setNickname("jack");
         }
        return sysUser;
    }

    @Override
    public Result findUserByToken(String token) {

        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(sysUser.getId());
        loginUserVo.setUserName(sysUser.getAccount());
        loginUserVo.setAvatar(sysUser.getAvatar());
        loginUserVo.setNickName(sysUser.getNickname());
        return Result.success(loginUserVo);
    }

    @Override
    public SysUser findUserByAccount(String userName) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getAccount,userName);
        wrapper.last("limit 1");
        return sysUserMapper.selectOne(wrapper);
    }

    @Override
    public void register(SysUser user) {
        sysUserMapper.insert(user);
    }
}
